package top.api.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import top.api.common.RedisKey;
import top.api.common.ResUlt;
import top.api.service.CommonService;
import top.api.utils.Base64CodeUtils;
import top.api.utils.RedisCache;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResUlt getPicBas64() {
        Map<String,String> map = Base64CodeUtils.getMathCodeMap();

        String base64Str = map.get("base64Str");
        String code = map.get("code");

        String uuid = UUID.randomUUID().toString();

        // 将正确验证码存入redis 3分钟过期
        String redisKey = RedisKey.getPicCodeKey() + ":" + uuid;

        redisCache.setCacheObject(redisKey,code,3, TimeUnit.MINUTES);

        HashMap<String,String> _map= new HashMap<>();
        _map.put("base64Str",base64Str);
        _map.put("uuid",uuid);

        return new ResUlt<Map<String,String>>(200,"获取成功!",_map);
    }

    @Override
    public ResUlt<Object> checkPicCode(String picCode,String uuid) {

        String redisKey = RedisKey.getPicCodeKey() + ":" + uuid;

        String code = redisCache.getCacheObject(redisKey);

        if (ObjectUtils.isEmpty(code)){
            return ResUlt.error("验证码已过期!");
        }

        // 校验是否正确
        if (! code.equals(picCode)){
            return ResUlt.error("验证码错误");
        }

        return ResUlt.success("验证码正确");
    }

}
